package com.lean.reptile.dynamichtml;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: Dynamichtml
 * @Description: 解析动态页面
 * @Author: zhanghongwei
 * @Date: 2022/6/9 19:30
 */
public class DynamicSpider {

    public static void main(String[] args) { // 设置必要参数
        DesiredCapabilities dcaps = new DesiredCapabilities();
        // ssl证书支持
        dcaps.setCapability("acceptSslCerts", true);
        // css搜索支持
        dcaps.setCapability("cssSelectorsEnabled", true);
        // js支持
        dcaps.setJavascriptEnabled(true);
        // 驱动支持
        dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "D:\\ruanjian\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe");
        // // 创建无界面浏览器对象
        WebDriver driver = new PhantomJSDriver(dcaps);
        try {
            // 让浏览器访问空间主页
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            driver.get("https://item.jd.com/4391570.html");
            Thread.sleep(5000l);
            String html = driver.getPageSource();
            Writer out = new FileWriter(new File("./doc/httpclient.html"));
            out.write(html);
            out.close();
            WebElement element = driver.findElement(By.xpath("/html/body/div[5]/div/div[2]/div[4]/div/div[1]/div[2]/span[1]/span[2]"));
            System.out.println(element.getText());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // 关闭并退出浏览器
            driver.close();
            driver.quit();
        }
    }

}
